<?php 
include('includes/connexion.php');
$adminmanager = new AdminManager($connexion);
$elevemanager = new EleveManager($connexion);
session_start();
include('includes/secu.php');
if(!isset($_SESSION['Admin']))
	header('Location: login.php');
?>
<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
  <title>Tables Advanced - Target Admin</title>

  <meta charset="utf-8">
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width">

  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,700italic,400,600,700">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Oswald:400,300,700">
  <link rel="stylesheet" href="./css/font-awesome.min.css">
  <link rel="stylesheet" href="./js/libs/css/ui-lightness/jquery-ui-1.9.2.custom.min.css">
  <link rel="stylesheet" href="./css/bootstrap.min.css">

  <!-- Plugin CSS -->
  <link rel="stylesheet" href="./js/plugins/icheck/skins/minimal/blue.css">
  <link rel="stylesheet" href="js/plugins/select2/select2.css">
  <link rel="stylesheet" href="js/plugins/datepicker/datepicker.css">
  <link rel="stylesheet" href="js/plugins/simplecolorpicker/jquery.simplecolorpicker.css">
  <link rel="stylesheet" href="js/plugins/timepicker/bootstrap-timepicker.css">
  <link rel="stylesheet" href="js/plugins/fileupload/bootstrap-fileupload.css">
  <link rel="stylesheet" href="js/libs/css/ui-lightness/jquery-ui-1.9.2.custom.css">
  <link rel="stylesheet" href="js/plugins/magnific/magnific-popup.css">
  <!-- App CSS -->
  <link rel="stylesheet" href="./css/target-admin.css">
  <link rel="stylesheet" href="./css/custom.css">
  <!-- Page CSS -->
  <link rel="stylesheet" href="css/demos/ui-notifications.css">

  <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
  <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
  <![endif]-->
</head>
<?php 

require_once('includes/connexion.php');
	$reponse = new ReponseManager($connexion);// on instancie une réponse avec la connexion en parametre
	$maQuestion= new QuestionManager($connexion); //  on instancie une question pour récupérer le nom de la question
	$monExercice = new ExerciceManager($connexion); // on instancie un exercice manager
	if(!empty($_GET['idQuestion'])){
		$idQuest = $_GET['idQuestion'];
	}else{
		$idQuest = $_POST['idRefQuestion'];
	}
	
	$tabReponse = $reponse->getByQuestion($idQuest); // on récupere la liste des réponse dans le tableau
	
	// on update un champ
	if(!empty($_POST['ReponseUpdate'])){
		$mreponse = $reponse->get($_POST["idRepUpdate"]);
		if($_FILES['upload']['name'] != ""){
			$extensions_valides = array( 'jpg' , 'jpeg' , 'gif' , 'png' );
			$extension_upload = strtolower(substr(strrchr($_FILES['upload']['name'], '.'),1));// juste le type sans le . soit png, jpg....
			$chemin_destination = 'uploadImages/'; // le chemin d'enregistrement    
			//RENAME
			$NewNomImage = uniqid('q_'); // nouveau nom !
			$testValide = false; 
			foreach($extensions_valides as $value){ // on test si l'extension est valide
				if($extension_upload == $value){
					$testValide = true;
				}
			}
			
			if($testValide){
				//UPLOAD
				move_uploaded_file($_FILES['upload']['tmp_name'], $chemin_destination.$NewNomImage.".".$extension_upload);	
				$mreponse->setImage($chemin_destination.$NewNomImage.".".$extension_upload);	
			}
		}
		/*
		if($_POST['zonetxt']){ // on regarde si la case est cochée
			$maReponse->setZoneTxt('1');
		}else{$maReponse->setZoneTxt('0');}
		*/
		$mreponse->setContenu($_POST['ReponseUpdate']);
		$mreponse->setCorrecte($_POST['CorrecteUpdate']);
		var_dump($mreponse);
		$reponse->update($mreponse);
		header('Location:reponseRelations.php?idQuestion='.$idQuest);			
	}
	
	//Si on modifie l'odre des réponses
	if(!empty($_GET['ordre']) && !empty($_GET['id'])){
		$rep = $reponse->get($_GET['id']);
		
		if ($_GET['ordre']=="up"){
			$reponse->ordreUp($rep->id());
		} else if($_GET['ordre'] == "down"){
			$reponse->ordreDown($rep->id());
		}
		header('Location:reponseRelations.php?idQuestion='.$idQuest); // on redirige	
	}
	
	// si les champs del et id existent on supprimer la réponse.
	if(!empty($_GET['del']) && !empty($_GET['id'])){
		$rep = $reponse->get($_GET['id']);
		if (file_exists($rep->image())){
			unlink($rep->image());
		}
		$reponse->delete($rep); // on supprime la réponse
		$reponse->ReorganizeOrdre($idQuest);
		header('Location:reponseRelations.php?idQuestion='.$idQuest); // on redirige
		
	}  	

	
    // si les champs sont remplis on ajoute à la bdd         	
	if(!empty($_POST['Reponse'])){
		
		
		if($_POST['correcte'] == "PAS INTRUT"){$corr = 1;} else{$corr = 0;} // si on a coché juste on retourne 1 sinon 0
		
		
		if(isset($_FILES['upload']) && !empty($_FILES['upload']['name'])){
			
			$extensions_valides = array( 'jpg' , 'jpeg' , 'gif' , 'png' );
			$extension_upload = strtolower(  substr(  strrchr($_FILES['upload']['name'], '.')  ,1)  );// juste le type sans le . soit png, jpg....
			$chemin_destination = 'uploadImages/'; // le chemin d'enregistrement    
			//RENAME
			$nomImage = $_FILES['upload']["name"];
			$NewNomImage = uniqid('r_'); // nouveau nom !
			$testValide = false; 
			foreach($extensions_valides as $value){ // on test si l'extension est valide
				if($extension_upload == $value){
					$testValide = true;
				}
			}
			
			if($testValide){
				//UPLOAD
				move_uploaded_file($_FILES['upload']['tmp_name'], $chemin_destination.$NewNomImage.".".$extension_upload);	
				$chemin = $chemin_destination.$NewNomImage.".".$extension_upload;	
			}
		}
		$maReponse = new Reponse(); // on créé une nouvelle réponse
		
		/*
		if($_POST['zonetxt']){ // on regarde si la case est cochée
			$maReponse->setZoneTxt('1');
		}else{$maReponse->setZoneTxt('0');}
		*/

		$maReponse->setIdRefQuestion($_POST['idRefQuestion']); // on ajoute la référence à la question
		$maReponse->setCorrecte($corr); // on ajoute la référence à la question
		
		if(isset($_FILES['upload']) && !empty($_FILES['upload']['name'])){
			$maReponse->setImage($chemin); // on ajoute l'image de la réponse
		}
		else {$maReponse->setImage("Aucune image");}// on ajoute un texte si pas d'image de la réponse
		
		if(!empty($_POST['Reponse'])){
			$maReponse->setContenu($_POST['Reponse']);// on ajoute la réponse
		}
		else{$maReponse->setContenu("NoText");} // on ajoute NoText si pas de question
		
		
		
		$reponse->add($maReponse); // on ajoute la réponse à la bdd
		
		header('Location:reponseRelations.php?idQuestion='.$idQuest); // on redirige			
	}
				
?>
<body>

<?php include('includes/navbar.php'); ?>

<?php include('includes/mainbar.php'); ?>

<div class="container">

  <div class="content">

    <div class="content-container">

      <div class="content-header">
        <h2 class="content-header-title">Réponses</h2>
             <a href="gestion.php">Tests</a>
             / 
             <a href="listexercice.php">Exercices</a> 
             /  
             <a href="question.php?idExercice=<?php echo $maQuestion->get($idQuest)->idRefExercice(); ?>">Questions</a> 
             / 
             Réponses
      </div> <!-- /.content-header --> 

      <div class="row">

        <div class="col-md-12">

          <div class="portlet">

            <div class="portlet-header">

              <h3>
                <i class="fa fa-table"></i>
                Liste des réponses de la question "<?php echo $maQuestion->get($idQuest)->contenu(); ?>"
              </h3>

            </div> <!-- /.portlet-header -->

            <div class="portlet-content">           

              <div class="table-responsive">
	  <table class="table table-striped table-bordered table-hover table-highlight table-checkable" 
                data-provide="datatable" 
                data-display-rows="10"
                data-info="true"
                data-search="true"
                data-length-change="true"
                data-paginate="true">
      	<thead>
	    <tr>
            <th data-filterable="false">OPTION</th>
			<th data-filterable="false">REPONSE</th>
            <th data-filterable="false">ETAT</th>
            <th data-filterable="false" data-sortable="true" data-direction="asc">ORDRE</th>
        </tr>
        </thead>
        <tbody>
        <?php 
		
       	foreach($tabReponse as $rep){			
			
			echo "<tr id='reponse".$rep->id()."'>";
			echo "<td align='center'>";
					?><a data-toggle="modal" href="#ModifReponse" class="fa fa-gear" id="reponse<?php echo $rep->id(); ?>"></a> <a href ='?idQuestion=<?php echo $idQuest; ?>&del=1&id=<?php echo $rep->id(); ?>' style='color:red;' onclick="return(confirm('Etes-vous sûr de vouloir supprimer cette réponse ?'));"><span class="fa fa-trash-o"></span></a><?php
			echo "</td>";
				if(isset($_GET['idRepUpdate']) || !empty($_GET['idRepUpdate']) ) {
				  echo "<td></td>";
				}
			echo "<td>";
			if($rep->contenu() === "NoText"){
			}else {		
				echo $rep->contenu().' ';			
				}

			echo "</td>";
			
			
			if($rep->correcte() == 1){echo "<td style='color:green;'>PAS INTRUT</td>";}else{echo "<td style='color:red;'>INTRUT</td>";}
			echo "<td>";
			echo "<a href ='reponseRelations.php?id=".$rep->id()."&ordre=up&idQuestion=".$idQuest."' style='color:blue;'><span class='fa fa-angle-double-up'></span></a> ";
			echo $rep->ordre();
			echo " <a href ='reponseRelations.php?id=".$rep->id()."&ordre=down&idQuestion=".$idQuest."' style='color:blue;'><span class='fa fa-angle-double-down'></span></a></td>";
			echo "</tr>";
		}
		
		?></tbody><?php
        if(!isset($_GET['idRepUpdate']) || empty($_GET['idRepUpdate']) ){
        ?>
       
	    <tr>
         
          	<form action="reponseRelations.php" method="post" enctype="multipart/form-data">
            	  <td align="center"><input type="submit" class="btn btn-success" value="Ajouter une Réponse"/></td>           
                  <td>
                  	<input type="text" id="text-input" class="form-control" name="Reponse" />
                    <!-- <input type="checkbox" name="zonetxt" /> Cochez si vous souhaitez insérer une zone de texte pour la réponse -->
                  </td>
                  
                  <td><select name="correcte" id="select-input" class="form-control"><option>PAS INTRUT</option><option selected>INTRUT</option></select></td>
                  <td></td>
                  <input type="hidden" value ="<?php echo $idQuest; ?>" name="idRefQuestion"/>
            </form>
          
        </tr>
        <?php } ?>
      </table>
              
              </div> <!-- /.table-responsive -->

            </div> <!-- /.portlet-content -->

          </div> <!-- /.portlet -->

        </div> <!-- /.col -->

      </div> <!-- /.row -->

    </div> <!-- /.content-container -->
      
  </div> <!-- /.content -->

</div> <!-- /.container -->


<?php include('includes/footer.php'); ?>

  <script src="./js/libs/jquery-1.10.1.min.js"></script>
  <script src="./js/libs/jquery-ui-1.9.2.custom.min.js"></script>
  <script src="./js/libs/bootstrap.min.js"></script>

  <!--[if lt IE 9]>
  <script src="./js/libs/excanvas.compiled.js"></script>
  <![endif]-->
  
  <!-- Plugin JS -->
  <script src="./js/plugins/datatables/jquery.dataTables.min.js"></script>
  <script src="./js/plugins/datatables/DT_bootstrap.js"></script>
  <script src="./js/plugins/tableCheckable/jquery.tableCheckable.js"></script>
  <script src="./js/plugins/icheck/jquery.icheck.min.js"></script>
  <script src="js/plugins/magnific/jquery.magnific-popup.min.js"></script>

  <!-- App JS -->
  <script src="./js/target-admin.js"></script>
  
<div id="ModifReponse" class="modal modal-styled fade">
  <div class="modal-dialog">
    <div class="modal-content">
    <form action="reponseRelations.php?idQuestion=<?php echo $idQuest; ?>" id="mformreponse" method="post" class="form parsley-form" enctype="multipart/form-data">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h3 class="modal-title">Modification de l'exercice</h3>
      </div>
      <div class="modal-body">
      	<div class="row">
              <div class="col-md-8">
              <label for="ReponseUpdate">Contenu</label><input type="text" name="ReponseUpdate" />
              </div>
            <div class="col-md-4">
            <label for="CorrecteUpdate">Correcte</label><select name="CorrecteUpdate" class="form-control">
                    <option value="0">INTRUT</option>
                    <option value="1">PAS INTRUT</option>
                  </select>
            </div>
        </div>
        <div class="row">
        	<div class="col-md-12"><input type="file" name="upload"/></div>
        </div>
      </div>
      <div class="modal-footer">
      	<input type="text" name="idRepUpdate" hidden/>
        <button type="button" class="btn btn-tertiary" data-dismiss="modal">Fermer</button>
        <input type="submit" class="btn btn-primary" name="mformreponse" value="Sauvegarder"/>
      </div>
      </form>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<script type="text/javascript">
$(document).ready(function() {
	$("a[id^='reponse']").click(function() {
		
		var id = $(this).attr("id").split("reponse");

		var rep2 = '#reponse'+id[1]+' td+td';
		var rep5 = '#reponse'+id[1]+' td+td+td+td';
		
		$("#mformreponse input[name=idRepUpdate]").val(id[1]);		
				
		$("#mformreponse input[name=ReponseUpdate]").val($(rep2).html());
		
		if($(rep5).html() == 'JUSTE'){ var rep = 1; }else{ var rep = 0;}
		$("#mformreponse select[name=CorrecteUpdate]").val(rep);
	});
});
</script>

  
</body>
</html>